package com.flydog.mall.service.impl.pms;

import com.flydog.mall.common.api.PageResponse;
import com.flydog.mall.dto.PmsProductAttributeParam;
import com.flydog.mall.entity.pms.PmsProductAttribute;
import com.flydog.mall.entity.pms.PmsProductAttributeCategory;
import com.flydog.mall.repository.pms.PmsProductAttributeCategoryRepository;
import com.flydog.mall.repository.pms.PmsProductAttributeRepository;
import com.flydog.mall.service.pms.PmsProductAttributeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Optional;

/**
 * @author Cao
 * @description 商品属性服务实现
 * @create 2021-03-24
 */

@Service
@Slf4j
public class PmsProductAttributeServiceImpl implements PmsProductAttributeService {

    @Autowired
    private PmsProductAttributeRepository attributeRepository;

    @Autowired
    private PmsProductAttributeCategoryRepository attributeCategoryRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int create(PmsProductAttributeParam param) {
        PmsProductAttribute attribute = new PmsProductAttribute();
        BeanUtils.copyProperties(param, attribute);
        Optional<PmsProductAttributeCategory> categoryOptional = attributeCategoryRepository.findById(attribute.getProductAttributeCategoryId());
        if (categoryOptional.isPresent()) {
            PmsProductAttributeCategory category = categoryOptional.get();
            log.info(attribute.toString());
            switch (attribute.getType()) {
                case 0:
                    Integer originalAttrCount = category.getAttributeCount();
                    category.setAttributeCount(originalAttrCount + 1);
                    break;
                case 1:
                    Integer originalParamCount = category.getParamCount();
                    category.setParamCount(originalParamCount + 1);
                    break;
                default:
                    break;
            }
            attributeCategoryRepository.save(category);
        }
        attributeRepository.save(attribute);
        return 1;
    }

    @Override
    public Optional<PmsProductAttribute> getById(Long id) {
        return attributeRepository.findById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(Long id, PmsProductAttributeParam param) {
        PmsProductAttribute newAttribute = new PmsProductAttribute();
        BeanUtils.copyProperties(param, newAttribute);
        Optional<PmsProductAttribute> originalAttrOptional = attributeRepository.findById(id);

        if (originalAttrOptional.isPresent()) {
            PmsProductAttribute originalAttr = originalAttrOptional.get();
            //如果修改后的属性改变了分类，则需改变原分类信息和现分类信息（属性数或参数数）
            if (!originalAttr.getProductAttributeCategoryId().equals(newAttribute.getProductAttributeCategoryId())) {
                //属性分类被改变
                Optional<PmsProductAttributeCategory> originalCategoryOptional = attributeCategoryRepository.findById(originalAttr.getProductAttributeCategoryId());
                Optional<PmsProductAttributeCategory> newCateOptional = attributeCategoryRepository.findById(newAttribute.getProductAttributeCategoryId());
                if (originalCategoryOptional.isPresent() && newCateOptional.isPresent()) {
                    PmsProductAttributeCategory originalCate = originalCategoryOptional.get();
                    PmsProductAttributeCategory newCate = newCateOptional.get();
                    switch (originalAttr.getType()) {
                        case 0:
                            int originalAttrCount = originalCate.getAttributeCount();
                            int newAttrCount = newCate.getAttributeCount();
                            originalCate.setAttributeCount(originalAttrCount - 1);
                            newCate.setAttributeCount(newAttrCount + 1);
                            break;
                        case 1:
                            int originalParamCount = originalCate.getParamCount();
                            int newParamCount = newCate.getParamCount();
                            originalCate.setParamCount(originalParamCount - 1);
                            newCate.setParamCount(newParamCount + 1);
                            break;
                        default:
                            break;
                    }
                    attributeCategoryRepository.save(originalCate);
                    attributeCategoryRepository.save(newCate);
                }
            }
        }
        newAttribute.setId(id);
        attributeRepository.save(newAttribute);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long[] ids) {
        Arrays.stream(ids).forEach(this::delete);
        return ids.length;
    }

    @Override
    public PageResponse<PmsProductAttribute> getListByCidAndType(Long cid, Integer type, Integer pageNum, Integer pageSize) {
        return PageResponse.restPage(attributeRepository.findByProductAttributeCategoryIdAndType(cid, type, PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "sort")));
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Optional<PmsProductAttribute> productAttributeOptional = attributeRepository.findById(id);
        if(productAttributeOptional.isPresent()){
            PmsProductAttribute attribute = productAttributeOptional.get();
            Optional<PmsProductAttributeCategory> categoryOptional = attributeCategoryRepository.findById(attribute.getProductAttributeCategoryId());
            if(categoryOptional.isPresent()){
                PmsProductAttributeCategory category = categoryOptional.get();
                switch (attribute.getType()) {
                    case 0:
                        int attrCount = category.getAttributeCount();
                        category.setAttributeCount(attrCount - 1);
                        break;
                    case 1:
                        int paramCount = category.getParamCount();
                        category.setParamCount(paramCount - 1);
                        break;
                    default:
                        break;
                }
                attributeCategoryRepository.save(category);
            }
        }
        attributeRepository.deleteById(id);
    }
}
